import {Component, OnInit} from '@angular/core';
import {FetchService} from "../../../core/net/fetch.service";
import * as _ from "lodash";
import * as moment from "moment";
import {OneMapService} from "../../one-map/one-map.service";
import {FormBuilder, FormGroup} from "@angular/forms";
import {NzMessageService} from "ng-zorro-antd";
import {format, startOfMonth, endOfMonth, subMonths, subDays} from 'date-fns';
import {UtilService} from '../../../core/util/util.service';

@Component({
  selector: 'app-agri-canal',
  templateUrl: './agri-canal.component.html',
  styleUrls: ['./agri-canal.component.scss']
})
export class AgriCanalComponent implements OnInit {
  radioValue = 'single';
  listData = [];
  stadiaCode: string; //  当前测站编码
  sectionCode: string;
  stationName = '';
  topDateModal = [startOfMonth(subMonths(new Date(), 1)), subDays(new Date(), 1)];
  topDateRanges = {
    '昨日': [
      moment().subtract(1, 'days').valueOf(),
      moment().subtract(1, 'days').valueOf()
    ],
    '3日': [
      moment().subtract(3, 'days').valueOf(),
      new Date()
    ],
    '7日': [
      moment().subtract(7, 'days').valueOf(),
      new Date()
    ],
    '本月': [
      moment().startOf('month').valueOf(),
      new Date()
    ],
    '上月': [
      moment().subtract(1, 'months').startOf('month').valueOf(),
      moment().subtract(1, 'months').endOf('month').valueOf()
    ],
    '近3月': [
      moment().subtract(3, 'months').startOf('month').valueOf(),
      new Date()
    ],
  };
  processOpt: any = {
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {
          show: true,
          excludeComponents: ['toolbox'],
          pixelRatio: 2
        }
      }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        animation: false,
        label: {
          backgroundColor: "#505765"
        }
      }
    },
    legend: {
      data: ["水位", "流量"],
      bottom: 10
    },
    xAxis: {
      type: "category",
      data: []
    },
    yAxis: [
      {
        name: "水位(m)",
        type: "value"
      },
      {
        name: "流量(m³/s)",
        type: "value"
      }
    ],
    series: [
      {
        name: "水位",
        type: "line",
        smooth: true,
        data: []
      },
      {
        name: "流量",
        type: "line",
        yAxisIndex: 1,
        smooth: true,
        data: []
      }
    ]
  };
  processOptChange: any = {};
  processEchartsIntance: any;
  waterLevelDateModal = [startOfMonth(subMonths(new Date(), 1)), subDays(new Date(), 1)];
  featureForm: FormGroup;

  /*****************  旬月特征值对比  *********************/
  monthForm: FormGroup;
  startValue: Date | null = null;
  endValue: Date | null = null;
  endOpen = false;
  monthData: any = {};
  monthOpt: any = {
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {
          show: true,
          excludeComponents: ['toolbox'],
          pixelRatio: 2
        }
      }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      data: [],
      bottom: 0
    },
    grid: {
      top: "10%",
      bottom: "8%",
      left: "6%",
      right: "4%",
      containLabel: true
    },
    xAxis: {
      type: "category",
      data: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"]
    },
    yAxis: {
      type: "value"
    },
    series: []
  };
  monthOptChange: any = {};
  /******************* end *******************/

  /******************* 监测数据 *******************/
  tableData = [];
  pageNum = 1;
  pageSize = 25;
  /******************* end *******************/


  /******************* 历史同期对比 *******************/
  historyForm: FormGroup;
  historyYearList = [];
  startHistoryValue: Date | null = null;
  endHistoryValue: Date | null = null;
  endHistoryOpen = false;
  historyOpt: any = {
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {
          show: true,
          excludeComponents: ['toolbox'],
          pixelRatio: 2
        }
      }
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      data: []
    },
    xAxis: {
      type: "category",
      data: []
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        type: "line",
        data: []
      }
    ]
  };
  historyOptChange: any = {};

  /******************* end *******************/
  constructor(private fetchService: FetchService,
              private mapService: OneMapService,
              private message: NzMessageService,
              private util: UtilService,
              private fb: FormBuilder) {
    this.featureForm = this.fb.group({
      alertWl: [''],
      limitWl: [''],
      maxWl: [''],
      minWl: [''],
      maxTime: [''],
      minTime: [''],
      avgWl: [''],
      medianWl: [''],
      last3AvgWl: [''],
      last3MedianWl: [''],
      last3MedianPer: [''],
      last3AvgPer: [''],
    });
    this.monthForm = this.fb.group({
      valType: ['1'],
      dateType: ['1'],
      startYear: [moment().subtract(10, 'year').valueOf()],
      endYear: [new Date()],
      currYear: [moment().year()]
    });
    this.historyYearList = this.getLastSeveralYears();
    this.historyForm = this.fb.group({
      valType: ['1'],
      yearStr: [[moment().year()]],
      startDateStr: [moment().subtract(1, 'month').valueOf()],
      endDateStr: [new Date()],
    });
  }

  ngOnInit() {
    this.fetchService.get<any>('report/muwWf/listAllSite', {}).subscribe(res => {
      // console.log(res);
      this.listData = res;
      this.selectedAreaChanged(this.listData[0]);
    });
  }

  disabledStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.endValue) {
      return false;
    }
    return startValue.getTime() > this.endValue.getTime();
  };

  disabledEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.startValue) {
      return false;
    }
    return endValue.getTime() <= this.startValue.getTime();
  };

  onStartChange(date: Date): void {
    this.startValue = date;
  }

  onEndChange(date: Date): void {
    this.endValue = date;
  }

  handleStartOpenChange(open: boolean): void {
    if (!open) {
      this.endOpen = true;
    }
    // console.log('handleStartOpenChange', open, this.endOpen);
  }

  handleEndOpenChange(open: boolean): void {
    // console.log(open);
    this.endOpen = open;
  }

  /**********************  历史对比 ************************/
  disabledHistoryStartDate = (startValue: Date): boolean => {
    if (!startValue || !this.endHistoryValue) {
      return false;
    }
    return startValue.getTime() > this.endHistoryValue.getTime();
  };

  disabledHistoryEndDate = (endValue: Date): boolean => {
    if (!endValue || !this.startHistoryValue) {
      return false;
    }
    return endValue.getTime() <= this.startHistoryValue.getTime();
  };

  onStartHistoryChange(date: Date): void {
    this.startHistoryValue = date;
  }

  onEndHistoryChange(date: Date): void {
    this.endHistoryValue = date;
  }

  handleStartHistoryOpenChange(open: boolean): void {
    if (!open) {
      this.endHistoryOpen = true;
    }
  }

  handleEndHistoryOpenChange(open: boolean): void {
    this.endHistoryOpen = open;
  }

  /**********************************************/
  selectedAreaChanged(item): void {
    this.stationName = item.item;
    this.stadiaCode = item.id;
    this.sectionCode = item.sectionCode;
    this.queryInfo();
  }

  queryInfo(): void {
    // console.log(this.topDateModal);
    this.waterLevelDateModal = this.topDateModal;
    this.onQueryProcessList();
    this.onQueryMonthList();
    this.onQueryHistory();
  }

  private getItemValues(list, key) {
    return list.map(i => {
      return i[key] || 0;
    });
  }

  onQueryProcessList(): void {
    const params = {
      trId: this.stadiaCode,
      sectionCode: this.sectionCode,
      startDate: moment(this.waterLevelDateModal[0]).valueOf(),
      endDate: moment(this.waterLevelDateModal[1]).valueOf()
    };
    this.fetchService.post('report/muwWf/data', params).subscribe(res => {
      if (res) {
        const list = res["wrsMuwWfDatas"];
        res['minTime'] = moment(res['minTime']).format('YYYY-MM-DD HH:mm:ss');
        res['maxTime'] = moment(res['maxTime']).format('YYYY-MM-DD HH:mm:ss');
        this.featureForm.patchValue(res);
        const chartName = `${this.stationName}水位流量过程线`;
        this.processOptChange = {
          toolbox: {
            feature: {
              saveAsImage: {
                name: chartName
              }
            }
          },
          legend: {
            data: ["水位", "流量"],
            bottom: 10
          },
          xAxis: {
            data: list.map(o => {
              return moment(o.time).format('YYYY-MM-DD HH:mm:ss');
            })
          },
          yAxis: [
            {
              name: "水位(m)",
              type: "value",
              min: Math.floor(this.calcYAxisData('min', this.util.max(this.getItemValues(list, "wl")), this.util.min(this.getItemValues(list, "wl")))),
              max: Math.ceil(this.calcYAxisData('max', this.util.max(this.getItemValues(list, "wl")), this.util.min(this.getItemValues(list, "wl")))),
            },
            {
              name: "流量(m³/s)",
              type: "value",
              min: Math.floor(this.calcYAxisData('min', this.util.max(this.getItemValues(list, "flow")), this.util.min(this.getItemValues(list, "flow")))),
              max: Math.ceil(this.calcYAxisData('max', this.util.max(this.getItemValues(list, "flow")), this.util.min(this.getItemValues(list, "flow")))),
            }
          ],
          series: [
            {
              name: "水位",
              type: 'line',
              markPoint: {
                // symbol: 'diamond',
                symbolSize: 30,
                data: [
                  {
                    type: 'max',
                    name: '最大'
                  },
                  {
                    name: '最小',
                    type: 'min'
                  },
                ],
                label: {
                  normal: {
                    formatter: (p) => {
                      console.log(p);
                      return `${p.name}: ${p.value}m`;
                    }
                  }
                }
              },
              data: this.getItemValues(list, "wl")
            },
            {
              name: "流量",
              type: 'line',
              markPoint: {
                // symbol: 'diamond',
                symbolSize: 30,
                data: [
                  {
                    type: 'max',
                    name: '最大'
                  },
                  {
                    name: '最小',
                    type: 'min'
                  },
                ],
                label: {
                  normal: {
                    formatter: (p) => {
                      console.log(p);
                      return `${p.name}: ${p.value}m³/s`;
                    }
                  }
                }
              },
              data: this.getItemValues(list, "flow")
            }
          ]
        };
        list.forEach(item => {
          item['date'] = moment(item['time']).format('YYYY-MM-DD');
          item['time'] = moment(item['time']).format('HH:mm:ss');
        });
        this.tableData = list;
      }
    });
  }

  private calcYAxisData(type: string, max: number, min: number): number {
    if (type === 'max') {
      return max + (max - min) / 2;
    } else if (type === 'min') {
      return (min - (max - min)) >= 0 ? +(min - (max - min)) : 0;
    }
  }

  onQueryMonthList(): void {
    console.log(this.monthForm.value);
    const params = {
      trId: this.stadiaCode,
      startYear: moment(this.monthForm.value.startYear).year(),
      endYear: moment(this.monthForm.value.endYear).year(),
      dateType: this.monthForm.value.dateType,
      valType: this.monthForm.value.valType
    };
    this.fetchService.post('report/muwWf/monthXunCampare', params).subscribe(res => {
      if (res) {
        this.monthData = res;
        const chartName = `${this.stationName}旬月特征值对比`;
        this.monthOptChange = {
          toolbox: {
            feature: {
              saveAsImage: {
                name: chartName
              }
            }
          },
          legend: {
            data: this.monthData.map(o => {
              return o.year;
            })
          },
          xAxis: {
            data: this.monthData[0].data.map(o => {
              return o.m;
            })
          },
          series: this.monthData.map(o => {
            return {
              name: o.year,
              type: "bar",
              data: o.data.map(item => {
                return item.val;
              })
            };
          })
        };
      }
    });
  }

  onQueryHistory(): void {
    // console.log(this.historyForm.value);
    const params = {
      trId: this.stadiaCode,
      startDateStr: moment(this.historyForm.value.startDateStr).format('MM-DD'),
      endDateStr: moment(this.historyForm.value.endDateStr).format('MM-DD'),
      yearStr: this.historyForm.value.yearStr.join(','),
      valType: this.historyForm.value.valType
    };
    // console.log(params);
    this.fetchService.post('report/muwWf/historySameTimeCampare', params).subscribe(res => {
      if (res && Array.isArray(res)) {
        const chartName = `${this.stationName}历史同期对比`;
        this.historyOptChange = {
          toolbox: {
            feature: {
              saveAsImage: {
                name: chartName
              }
            }
          },
          legend: {
            data: res.map(o => {
              return o.year;
            })
          },
          xAxis: {
            data: res[0].data.map(o => {
              return moment(o.time).format("MM-DD HH:mm:ss");
            })
          },
          yAxis: {
            name: this.historyForm.value.valType === '1' ? '水位（m）' : '流量（m³/s）'
          },
          series: res.map(o => {
            return {
              name: o.year,
              type: "line",
              smooth: true,
              data: o.data.map(item => {
                return item.val;
              })
            };
          })
        };
      }
    });
  }

  private getLastSeveralYears(length = 10): Array<any> {
    const curYear = moment().year();
    const arr = [];
    for (let i = curYear - length; i <= curYear; i++) {
      arr.push(i);
    }
    return arr;
  }

  exportFile(): void {
    const params = {
      trId: this.stadiaCode,
      sectionCode: this.sectionCode,
      startDate: moment(this.waterLevelDateModal[0]).valueOf(),
      endDate: moment(this.waterLevelDateModal[1]).valueOf()
    };
    this.fetchService.export('report/muwWf/export', params).subscribe((res: any) => {
      const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
      const elink = document.createElement('a');

      elink.download = `干渠——${this.stationName}引水数据.xlsx`;
      elink.href = URL.createObjectURL(blob);
      document.body.appendChild(elink);
      elink.click();
      URL.revokeObjectURL(elink.href); // 释放URL 对象
      document.body.removeChild(elink);
    });
  }
}
